import { computed, watch } from 'vue'
import { useChatStore } from '../stores/chat'
import { useModelStore } from '../../shared/stores/model'
import { useUserStore } from '../../auth/stores/user'
import type { 
  ChatRequest, 
  ChatConfig
} from '../../../types/chat'

/**
 * 聊天消息管理组合式API
 * 现在基于Pinia store实现，提供更统一和健壮的聊天状态管理
 */
export function useChatMessages() {
  // 获取store实例
  const chatStore = useChatStore()
  const modelStore = useModelStore()
  const userStore = useUserStore()
  
  // 当前会话的消息
  const currentSessionMessages = computed(() => chatStore.currentSessionMessages)

  // 当前会话
  const currentSession = computed(() => chatStore.currentSession)

  // 是否有错误
  const hasError = computed(() => chatStore.hasError)

  /**
   * 发送消息
   */
  async function sendMessage(message: string, options: Partial<ChatRequest> = {}) {
    await chatStore.sendMessage(message, options)
  }

  /**
   * 创建新会话
   */
  async function createNewSession(title?: string) {
    return await chatStore.createNewSession(userStore.userId || 0, title)
  }

  /**
   * 切换到指定会话
   * @param sessionId 会话ID
   */
  async function switchSession(sessionId: string) {
    await chatStore.switchSession(sessionId)
  }

  /**
   * 删除会话
   * @param sessionId 要删除的会话ID
   */
  async function deleteSession(sessionId: string) {
    await chatStore.deleteSession(sessionId)
  }

  /**
   * 更新会话标题
   * @param sessionId 会话ID
   * @param title 新标题
   */
  async function updateSessionTitle(sessionId: string, title: string) {
    await chatStore.updateSessionTitle(sessionId, title)
  }

  /**
   * 清除当前会话的所有消息
   */
  async function clearCurrentSession() {
    await chatStore.clearCurrentSession()
  }

  /**
   * 清除所有消息
   */
  async function clearMessages() {
    await chatStore.clearMessages()
  }

  /**
   * 重新发送消息
   */
  async function resendMessage(messageId: string) {
    await chatStore.resendMessage(messageId)
  }

  /**
   * 编辑消息
   */
  async function editMessage(messageId: string, newContent: string) {
    await chatStore.editMessage(messageId, newContent)
  }

  /**
   * 停止流式传输
   */
  async function stopStreaming() {
    await chatStore.stopStreaming()
  }

  /**
   * 更新配置
   */
  function updateConfig(newConfig: Partial<ChatConfig>) {
    chatStore.updateConfig(newConfig)
  }

  /**
   * 清除错误
   */
  function clearError() {
    chatStore.clearError()
  }

  /**
   * 重试上次失败的消息
   */
  async function retryLastMessage() {
    await chatStore.retryLastMessage()
  }

  /**
   * 从后端加载用户的会话列表
   */
  async function loadSessionsFromBackend() {
    await chatStore.loadSessionsFromBackend(userStore.userId || 0)
  }

  /**
   * 从后端加载会话的消息历史
   */
  async function loadSessionMessagesFromBackend(sessionId: string) {
    await chatStore.loadSessionMessagesFromBackend(sessionId)
  }

  /**
   * 初始化聊天服务
   */
  async function initialize() {
    try {
      // 移除认证检查，直接初始化聊天服务
      // 使用model store获取模型列表
      await modelStore.loadModels()
      
      if (modelStore.models.length > 0) {
        const models = modelStore.models.map(model => model.name)
        chatStore.updateConfig({
          supportedModels: models,
          // 不覆盖默认模型，保持已保存的选择
          ...(chatStore.config.defaultModel ? {} : { defaultModel: models[0] }),
          // 只在没有当前模型ID时设置，保持已保存的选择
          ...(chatStore.config.currentModelId || !modelStore.models[0]?.id ? {} : { currentModelId: Number(modelStore.models[0].id) })
        })
      }
      
      // 确保用户状态已初始化
      userStore.initUserState()
      
      // 初始化聊天服务
      await chatStore.initialize(userStore.userId || 0)
      
      console.log('聊天服务初始化完成');
      
    } catch (error) {
      console.error('聊天服务初始化失败:', error);
    }
  }

  // 监听当前会话ID变化，加载会话消息
  watch(() => chatStore.currentSessionId, async (newSessionId, oldSessionId) => {
    if (newSessionId && newSessionId !== oldSessionId) {
      console.log('[会话管理] 当前会话ID变化', { newSessionId, oldSessionId });
      
      // 从后端加载会话的消息历史
      await loadSessionMessagesFromBackend(newSessionId)
    }
  })

  // 自动初始化
  initialize()

  return {
    // 状态
    chatState: chatStore.$state,
    currentSessionMessages,
    currentSession,
    hasError,
    
    // 方法
    sendMessage,
    createNewSession,
    switchSession,
    deleteSession,
    updateSessionTitle,
    clearCurrentSession,
    clearMessages,
    resendMessage,
    editMessage,
    stopStreaming,
    updateConfig,
    clearError,
    retryLastMessage,
    loadSessionsFromBackend,
    loadSessionMessagesFromBackend,
    initialize
  }
}